// 初始化
$(function() {
	$(window.document).zinit();
});

(function($) {

	// 修改全局设置
	// states:[1,2], 修改前: states[]=1&states[]=2, 修改后: states=1&states=2
	$.ajaxSettings.traditional = true;
	$.ajaxSettings.dataType = "json";

	// ueditor
	window.UEDITOR_HOME_URL = Utils.getBaseUrl("assets/libs/ueditor/");
	$.fn.zinit.plugins.add(function() {
		if (window.UEDITOR_CONFIG) {
			window.UEDITOR_CONFIG.serverUrl = Utils.getBaseUrl("actions/common/ueditor/exec/");
			return true;
		}
	});

	$.fn.zinit.plugins.add(function() {
		if (window.baidu && baidu.template) {
			// 设置左分隔符为 <#
			baidu.template.LEFT_DELIMITER='<#';
			// 设置右分隔符为 #>
			baidu.template.RIGHT_DELIMITER='#>';
			// 默认不转义, 如果需要转义, 调用Utils.encodeHtml()处理
			baidu.template.ESCAPE = false;
			return true;
		}
	});

	// 只有#号的链接, 不改变location.hash
	$.fn.zinit.nodes.add("a[href='#']", function() {
		$(this).click(function(e) { e.preventDefault(); });
	});
	// 不可编辑的输入框初始化
	$.fn.zinit.nodes.add("input.uneditable, textarea.uneditable", function() {
		$(this).uneditable(true);
	});

	// Utils.succTips / Utils.warnTips
	$.fn.zinit.plugins.add(function() {
		if (Utils && $.msger) { // bootstrap
			Utils.succTips = function(msg) {
				$.msger({ style:'warning', content:msg });
			};
			Utils.warnTips = function(msg) {
				$.msger({ style:'danger', content:msg });
			};
			return true;
		}
	});

	$.fn.zinit.plugins.add("zupload", function() {
		var o = this.defaults;
		o.url = Utils.getBaseUrl("actions/webfile/upload.json"); // 上传文件的URL
		o.error = function(e) {
			Utils.warnTips(e.message);
		};
	});

	/** 表单提交插件 **/
	$.fn.zinit.plugins.add(function() {
		if (!$.zajax) { return; }
		var o = $.zajax.defaults;
		o.fn.check = Utils.succ;
		o.fn.loading = {
			show: function() { this.button && this.button.addClass("doing"); },
			stop: function() { this.button && this.button.removeClass("doing");  }
		};
		o.fn.succTips = function(e, json) {
			var e = this;
			if (e.button) {
				var msg = e.succMessage || e.button.zoptions().succMessage;
				if (!msg) { msg = (e.message || e.button.zoptions().message || e.button.text()) + "成功！"; }
				Utils.succTips(msg);
			} else {
				// 不是点按钮导致的提交,不显示成功消息
			}
		};
		o.fn.failTips = function(json) {
			var e = this;
			if (e.button) {
				// 失败消息, 先取服务器返回的, 再取options.failMessage or 按钮data-options的failMessage
				// 再取options.message or 按钮data-options配置的message, 再取按钮的文字
				var msg = json && json.message;
				if (!msg) { msg = e.failMessage || e.button.zoptions().failMessage; }
				if (!msg) { msg = (e.message || e.button.zoptions().message || e.button.text()) + "失败！"; }
				if (e.failTipsOnButton) { // 失败消息是否显示到按钮上
					if ($.fn.warnning) { e.button.warnning(msg); }
					else if ($.fn.msger) { e.button.msger(msg); }
					else { Utils.warnTips(msg); }
				} else {
					Utils.warnTips(msg);
				}
			} else {
				// 显示失败消息
				var msg = json && json.message || e.failMessage;
				if (!msg) { msg = e.message ? e.message + "失败！" : "网络异常，请稍后重试！"; }
				Utils.warnTips(msg);
			}
		};
		o.fn.prehandle = function(callback) {
			if (!this.checkLogin) {
				callback(); return;
			}
			var url = $("meta[name=account-url]").attr("content");
			$.ajax($.extend({}, o.options, {
				url: url,
				success:function(json) {
					if (json.body) {
						callback();
					} else {
						var url = $("meta[name=login-view]").attr("content");
						var flag = url.indexOf("?") < 0 ? "?" : "&";
						var returnUrl = "back"; // encodeURIComponent(window.location.href);
						window.location.href = url + flag + "return=" + returnUrl;
					}
				}
			}));
		};
		o.fn.validate = function(callback) {
			var self = this;
			if ($.fn.zhhvalidate) {
				self.form.zhhvalidate(function(e) {
					if (e.passed) {
						callback();
					}
				});
			} else {
				callback();
			}
		};
		o.fn.upload = function(callback) {
			if (!this.form || !$.fn.zupload) { callback(); return; }
			var button = this.button;

			this.form.find("input.filebox-f[data-zupload]").each(function() {
				var me = $(this);
				var attr = me.attr("data-zupload");
				me.removeAttr("data-zupload");
				me.xcall("textbox").siblings("input[type=file]").attr("data-zupload", attr);
			});

			Utils.showLoading("正在上传第1个文件");
			this.form.zupload({
				find : function(o, key) {
					return $(this).find("input[type=file],img").filter(function() {
						var me = $(this);
						var input = me.attr(key);
						var matches = input != undefined && input != "false";
						if (matches && this.type == "file") {
							matches = this.files && this.files.length > 0;
							if (matches) {
								matches = me.val() != me.attr("last-upload");
							}
						}
						return matches;
					});
				},
				process: function(e) {
					// $.log.debug("--> " + "正在上传第"+(e.index+1)+"个文件("+e.percent+"%)");
					Utils.showLoading("正在上传第"+(e.index+1)+"个文件("+e.percent+"%)");
				},
				step: function(e) {
					$.log.debug(e.url);
					var $file = $(e.element);
					$file.attr("last-upload", $file.val());
				},
				done: function(e) {
					callback.call(this, e);
					Utils.stopLoading();
				},
				error:function(e) {
					if (button) {
						button.warnning(e.message);
					} else {
						Utils.warnTips(e.message);
					}
				}
			});
		};
		$.extend(o.options, {
			loading: false,
			checkLogin: false,
			failTipsOnButton: true, // 失败消息是否显示到按钮上
			dataType: "json",
			crossDomain: $.support.cors, // IE9 support.cors=false
			xhrFields: { withCredentials: true }
		});
		return true;
	});

	/** 右侧滑出详情页插件 **/
	$.fn.zinit.nodes.add("body", function() {
		var me = $(this);
		if ($.fn.zsidebar) {
			me.zsidebar("bind");
		}
	});

	/** 表单验证插件 **/
	$.fn.zinit.plugins.add("zhhvalidate", function() {
		var zv = this.defaults;
		// 自定义AJAX解析函数
		var originalParse = zv.ajax.parse;
		zv.ajax.parse = function(e, json) {
			if ($.isPlainObject(json)) {
				return { passed:Utils.succ(json), text:json.message };
			} else { // 调用原解析函数
				return originalParse.call(this, e, json);
			}
		};
		// 查找校验目标的提示文本
		// 查找顺序:
		// 1. data-vld="{ label:'xxx', ... }"
		// 2. class="vld-label"标签中的文本
		// 3. class="control-label"标签中的文本
		// 4. data-label
		// 5. placeholder
		zv.fn.findLabelText = function($target, options) {
			if (!options) { options = zv.fn.getTargetOptions($target); }
			if (options.label) {
				return options.label;
			}
			var $line = $target.closest(zv.selectors.line.join(","));
			var text = $line.find(zv.selectors.label.join(",")).eq(0).text();
			if (!text) { text = $target.attr("data-label"); }
			if (!text) { text = $target.attr("placeholder"); }
			// 替换掉前面的*和后面的:
			// 如 * 用户名 : 替换为用户名
			return text && $.trim(text).replace(/(^\*\s*|\s*[:：]$)/g, "");
		};
		zv.classes["line-error"] = "has-error";
		zv.bind.push({on:"focus", selector:"input[data-vld], textarea[data-vld], select[data-vld]", fn:function() {
			$(this).closest(zv.selectors.line.join(",")).addClass("vld-typing");
		}});
		zv.bind.push({on:"blur", selector:zv.selectors.target.join(","), fn:function() {
			$(this).closest(zv.selectors.line.join(",")).removeClass("vld-typing");
			zv.fn.doBlurValidate.call(this);
		}});
		// 根据浏览器决定国际化语言
		var locals = [];
		for (var key in zv.locals) {
			locals.push(key);
		}
		zv.lang = $.zhh.resolveLocale("en", locals); // 英语优先
	});
	$.fn.zinit.nodes.add("form", function() {
		var me = $(this);
		if ($.fn.zhhvalidate) {
			me.zhhvalidate("init");
		}
	});
	
	/** 多选文字显示省略号: <div data-ellipsis="2"></div> **/
	$.fn.zinit.nodes.add("[data-ellipsis]", function() {
		if (window.$clamp) {
			var me = $(this);
			me.attr("title", me.text());
			var line = me.attr("data-ellipsis") * 1;
			$clamp(this, {clamp: line});
		}
	});
	$.fn.zinit.nodes.add(".ellipsis", function() {
		var me = $(this);
		me.attr("title", me.text());
	});

	/** 星级评价插件通用配置及自动初始化<div class="star-rating" data-options="half:true,number:3"></div> **/
	$.fn.zinit.nodes.add(".star-rating, .do-raty", "raty");
	$.fn.zinit.plugins.add("raty", function() {
		this.defaults.path = Utils.getBaseUrl("assets/libs/jquery-raty/star/");
		this.defaults.hints = [];
		this.defaults.targetType = "score";
		this.defaults.size = 24;
	});
	
	/** 日期选择插件 **/
	$.fn.zinit.nodes.add(".do-datepicker", "datepicker");
	$.fn.zinit.plugins.add("datepicker", function() {
		this.defaults.todayHighlight = true;
		this.defaults.format = "yyyy-mm-dd";
		if (this.dates['zh-CN']) {
			this.dates['zh-CN'].format = "yyyy-mm-dd";
			this.dates['zh-CN'].today = "今天";
		}
		this.defaults.language = $.zhh.resolveLocale([ "en", "zh-CN", {"zh-TW":"zh-Hant,zh-HK,zh-MO,zh-TW"} ]);
	});
	
	
	/** iCheck插件 **/
	$.fn.zinit.nodes.add(".do-icheck", function() {
		var me = $(this);
		if ($.fn.iCheck) {
			me.iCheck($.extend({}, $.fn.iCheck.zdefaults, me.zoptions()));
		}
	});
	$.fn.zinit.plugins.add("iCheck", function() {
		this.zdefaults = { 
			checkboxClass: 'icheckbox_minimal-blue',
			radioClass: 'iradio_minimal-blue'
		};
	});
	
	/** select2插件 **/
	$.fn.zinit.plugins.add("select2", function() {
		this.defaults.set("language", $.zhh.resolveLocale([ "en", "zh-CN", {"zh-TW":"zh-Hant,zh-HK,zh-MO,zh-TW"} ]));
		this.defaults.set("theme", "bootstrap");
	});
	$.fn.zinit.nodes.add(".do-select2", function() {
		if ($.fn.select2) {
	    	var me = $(this);
	    	me.select2(me.zoptions());
	    	// form.clearForm事件
	    	me.on("clear", function() {
	    		me.val("").trigger("change");
	    	});
		}
	});

	// DataTable
	$.fn.zinit.nodes.add("table[data-table]", function() {
		var me = $(this);
		var options = me.zoptions("table");
		if (options.init === false) { return; }
		if ($.fn.dataTable && $.fn.xtable) {
			me.xtable();
		}
	});
	$.fn.zinit.plugins.add(function() {
		if ($.fn.dataTable && $.fn.xtable) {
			var language = undefined;
			var locale = $.zhh.resolveLocale(["en", "zh"]);
			if (locale == "zh") {
				language = {
					infoFiltered: "(从 _MAX_ 条数据中检索)",
					lengthMenu: "每页显示  _MENU_ 条记录",
					info: "共 _TOTAL_ 条 / 显示第_START_到_END_条",
					emptyTable: "&nbsp;",
					zeroRecords: "抱歉， 没有找到数据",
					infoEmpty: "抱歉， 暂无数据",
					paginate: { first: "首页", previous: "上页", next: "下页", last: "末页" }
				};
			}
			$.fn.xtable.power({
				xtable: {
					totalField: "extra.total",
					listField: "body"
				},
				language: language
			});
			return true;
		}
	});
})(jQuery);
